package com.dd.cloud.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.utils.ValidatorUtils;
import com.dd.cloud.user.DTO.CallbackPresStatusReq;
import com.dd.cloud.user.DTO.CancelPresReq;
import com.dd.cloud.user.DTO.CommonParamReq;
import com.dd.cloud.user.entity.aicms.AicmsDiagnosticResult;
import com.dd.cloud.user.entity.order.OrderPay;
import com.dd.cloud.user.entity.pres.DrugsDirectory;
import com.dd.cloud.user.entity.pres.DrugsPoison;
import com.dd.cloud.user.entity.pres.PresBasics;
import com.dd.cloud.user.req.pres.*;
import com.dd.cloud.user.res.drugs.DrugsBasicBatchRes;
import com.dd.cloud.user.res.order.PayOrderResponse;
import com.dd.cloud.user.res.pres.*;
import com.dd.cloud.user.service.doctor.IBindReviewPresDoctorService;
import com.dd.cloud.user.service.phar.pharservice.PharServiceBeanInterface;
import com.dd.cloud.user.service.phar.pharservice.PharServiceInterface;
import com.dd.cloud.user.service.pres.*;
import com.dd.cloud.user.vo.ExpressRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 处方表 前端控制器
 * </p>
 *
 * @author czg
 * @since 2022-04-27
 */
@RestController
@RequestMapping("/pres")
@Validated
@Slf4j
public class PresController {
    @Autowired
    private IDrugsModelService drugsModelService;
    @Autowired
    private IDrugsPresAliasService drugsPresService;
    @Autowired
    private IPresPrescriptionService presPrescriptionService;
    @Autowired
    private IDrugsDirectoryService drugsDirectoryService;
    @Autowired
    private IDrugsPoisonService drugsPoisonService;
    @Autowired
    private PharServiceBeanInterface pharServiceBeanInterface;
    @Autowired
    private IPresHistoryService presHistoryService;

    @Autowired
    private IPresBasicsService presBasicsService;

    @Autowired
    private IBindReviewPresDoctorService bindReviewPresDoctorService;

    /**
     * 查询诊断记录 多条件查询
     *
     * @return 诊断记录
     */
    @GetMapping("/set/pinyin")
    public ResponseEntity<IPage<AicmsDiagnosticResult>> queryDiagnosticsTerms() {
        drugsModelService.setDrugsPinyin();
        return ResponseEntity.ok().build();
    }


    /**
     * 药品名查询药品用量范围
     *
     * @return 药品列表
     */
    @GetMapping("/drugs/dosage/batch")
    public ResponseEntity<List<DrugsDirectory>> drugsDosageBatch(String names) {
        List<DrugsDirectory> list = drugsDirectoryService.getDrugsDirectoryByNames(names);
        return ResponseEntity.ok(list);
    }

    /**
     * 查询有毒药品
     *
     * @return 药品列表
     */
    @GetMapping("/drugs/poison/batch")
    public ResponseEntity<List<DrugsPoison>> drugsPoisonBatch(String names) {
        List<DrugsPoison> list = drugsPoisonService.getDrugsPoison(names);
        return ResponseEntity.ok(list);
    }

    /**
     * 保存处方
     *
     * @return
     */
    @PostMapping("/add")
    public ResponseEntity<PayOrderResponse<?>> savePres(@Valid @RequestBody Map<String, Object> map, HttpServletRequest request) {
        PayOrderResponse<?> response = presPrescriptionService.savePres(request, map);
        return ResponseEntity.ok(response);
    }


    /**
     * 保存处方
     * union app专用, union特性会将数组反序列化成对象 用全部json字符串接收
     *
     * @return
     */
    @PostMapping("/union/add")
    public ResponseEntity<PayOrderResponse<?>> savePres(@Valid @RequestBody String json, HttpServletRequest request) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        Map<String, Object> req = JSON.parseObject(jsonObject.getString("json"), Map.class);
        ValidatorUtils.verify(req, PresCreateReq.class);
        PayOrderResponse<?> response = presPrescriptionService.savePres(request, req);
        return ResponseEntity.ok(response);
    }

    /**
     * 生成处方pdf
     *
     * @param tencode
     */
    @PostMapping("/re/generate/pres/pdf")
    public ResponseEntity<Void> generatePresPdf(@NotBlank(message = "处方编号不能为空") String tencode) {
        presPrescriptionService.generatePresPdf(tencode);
        return ResponseEntity.ok().build();
    }

    /**
     * 医生审核无处方权处方
     *
     * @param req
     */
    @PostMapping("/doctor/review")
    public ResponseEntity<Void> doctorReviewPres(@Valid @RequestBody DoctorReviewPresReq req) {
        presPrescriptionService.doctorReviewPres(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 重新提交处方
     *
     * @param tencode 处方编号
     */
    @PostMapping("/doctor/re/submit")
    public ResponseEntity<Void> reSubmitPres(@NotBlank(message = "处方编号不能为空") String tencode) {
        presPrescriptionService.reSubmitPres(tencode);
        return ResponseEntity.ok().build();
    }

    /**
     * 批量关键字查询药品
     *
     * @return 处方详情
     */
    @GetMapping("/drugs/info/names")
    public ResponseEntity<Map<String, Object>> drugsInfoNames(@NotBlank(message = "药品名不能为空") String names, Integer pharId) {
        Map<String, Object> res = drugsModelService.drugsModelListByNameAndPharId(names, pharId);
        return ResponseEntity.ok(res);
    }

    /**
     * 查询处方列表
     *
     * @param req
     * @return
     */
    @GetMapping("/result/page")
    public ResponseEntity<IPage<PresPrescriptionPageRes>> queryPresPrescriptionPage(@Valid PresPrescriptionPageReq req) {
        IPage<PresPrescriptionPageRes> res = presPrescriptionService.queryPresPrescriptionPage(req);
        return ResponseEntity.ok(res);
    }

    /**
     * 查询处方列表联合处方草稿查询
     *
     * @param req
     * @return
     */
    @GetMapping("/result/history/page")
    public ResponseEntity<IPage<PresPrescriptionHistoryPageRes>> queryPresPrescriptionHistoryPage(@Valid PresPrescriptionPageReq req) {
        IPage<PresPrescriptionHistoryPageRes> res = presPrescriptionService.queryPresPrescriptionHistoryPage(req);
        return ResponseEntity.ok(res);
    }

    /**
     * 处方详情
     *
     * @return 处方详情
     */
    @GetMapping("/result/detail")
    public ResponseEntity<PresPrescriptionDetailRes> presResultDetail(@NotBlank(message = "处方编号不能为空") String tencode) {
        PresPrescriptionDetailRes res = presPrescriptionService.getPresDetail(tencode);
        return ResponseEntity.ok(res);
    }

    /**
     * 分页查询药品
     *
     * @return
     */
    @GetMapping("/drugs/page")
    public ResponseEntity<Page<DrugsModelPageRes>> getDrugsModelPage(@Valid PresPageReq req) {
        Page<DrugsModelPageRes> res = drugsModelService.getDrugsModelPage(req);
        return ResponseEntity.ok(res);
    }

    /**
     * 添加药品
     *
     * @return
     */
    @PostMapping("/drugs/add")
    public ResponseEntity<Void> addDrugsModel(@Valid @RequestBody DrugsModelAddReq req) {
        drugsModelService.addDrugsModel(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改药品
     *
     * @return
     */
    @PostMapping("/drugs/update")
    public ResponseEntity<Void> updateDrugsModel(@Valid @RequestBody DrugsModelUpdateReq req) {
        drugsModelService.updateDrugsModel(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改药品状态
     *
     * @return
     */
    @PostMapping("/drugs/update/status")
    public ResponseEntity<Void> updateStatusDrugsModel(@NotNull(message = "药品id不能为空") Integer id, @NotNull(message = "药品状态不能为空") Integer status) {
        drugsModelService.updateStatusDrugsModel(id, status);
        return ResponseEntity.ok().build();
    }

    /**
     * 导入中药材详细信息数据
     *
     * @param file     excel文件
     * @param pharFlag 药房标识
     * @return 导入经验方数据
     */
    @PostMapping("/drugs/import/excel")
    public ResponseEntity<Void> importExcelDrugs(MultipartFile file, @NotBlank(message = "药房标识不能为空") String pharFlag) {
        if (file == null && !"xx".equals(pharFlag)) {
            throw new ZekeException(400, "文件不能为空");
        }
        drugsModelService.importExcelDrugs(file, pharFlag);
        return ResponseEntity.ok().build();
    }

    /**
     * 导入药材处方数据
     *
     * @param file=
     */
    @PostMapping("/drugs/alias/import/excel")
    public ResponseEntity<Void> importDrugsPresData(@NotNull(message = "文件不能为空") MultipartFile file) {
        drugsPresService.importDrugsPresAliasData(file);
        return ResponseEntity.ok().build();
    }

    /**
     * 同步药材别名
     */
    @PostMapping("/drugs/alias/sync")
    public ResponseEntity<Void> drugsSyncAlias() {
        drugsPresService.drugsSyncAlias();
        return ResponseEntity.ok().build();
    }

    /**
     * 通用处方状态流转接口
     *
     * @return 通用处方状态流转接口
     */
    @RequestMapping(value = "/{flag}/status/report", method = {RequestMethod.GET, RequestMethod.POST})
    public Object statusReport(@PathVariable("flag") String flag, HttpServletRequest request) {
        CallbackPresStatusReq req = new CallbackPresStatusReq(flag, request);
        return presPrescriptionService.statusReport(req);
    }

    /**
     * 通用处方状态流转接口
     *
     * @return 通用处方状态流转接口
     */
    @RequestMapping(value = "/{flag}/express/report", method = {RequestMethod.GET, RequestMethod.POST})
    public Object expressCallback(@PathVariable("flag") String flag, HttpServletRequest request) {
        CommonParamReq req = new CommonParamReq(flag, request);
        return presPrescriptionService.expressCallback(req);
    }

    /**
     * 删除处方
     *
     * @return
     */
    @PostMapping("/del")
    public ResponseEntity<Void> delPres(String tencode) {
        presPrescriptionService.updatePresStatus(tencode);
        return ResponseEntity.ok().build();
    }

    /**
     * 取消处方
     *
     * @return
     */
    @PostMapping("/cancel")
    public ResponseEntity<Void> cancelPres(CancelPresReq req) {
        presPrescriptionService.cancelPres(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 发送处方
     *
     * @return
     */
    @PostMapping("/send")
    public ResponseEntity<Void> sendPres(OrderPay pay) {
        PharServiceInterface pharServiceInterface = pharServiceBeanInterface.getPharService(pay);
        if (pharServiceInterface != null) {
            //药房处理的service获取失败
            pharServiceInterface.sendPresToPhar(pay);
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 查询处方订单信息h5
     *
     * @param tencode
     * @return
     */
    @GetMapping("/detail/h5")
    public ResponseEntity<PresDetailH5Res> queryPresDetailH5(@NotBlank(message = "处方编号不能为空") String tencode) {
        PresDetailH5Res res = presPrescriptionService.queryPresDetailH5(tencode);
        return ResponseEntity.ok(res);
    }

    /**
     * 查询物流信息
     *
     * @param tencode
     * @return
     */
    @GetMapping("/express/detail")
    public ResponseEntity<List<ExpressRes>> queryLogisticsInfo(@NotBlank(message = "处方编号不能为空") String tencode) {
        List<ExpressRes> res = presPrescriptionService.queryLogisticsInfo(tencode);
        return ResponseEntity.ok(res);
    }

    /**
     * 处理处方流转状态 药房后台
     *
     * @param req
     */
    @PostMapping("/handle/pharmacy")
    public ResponseEntity<Void> handlePresPharmacy(@Valid @RequestBody HandlePresPharmacyReq req) {
        presPrescriptionService.handlePresPharmacy(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改处方历史草稿
     *
     * @param req
     */
    @PostMapping("/history/add")
    public ResponseEntity<Void> createPresHistory(@Valid @RequestBody PresHistoryCreateReq req) {
        presHistoryService.createPresHistory(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改处方历史草稿
     *
     * @param req
     */
    @PostMapping("/history/update")
    public ResponseEntity<Void> updatePresHistory(@Valid @RequestBody PresHistoryUpdateReq req) {
        presHistoryService.updatePresHistory(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改处方历史草稿状态
     *
     * @param id
     * @param status
     */
    @PostMapping("/history/update/status")
    public ResponseEntity<Void> updatePresHistoryStatus(@NotNull(message = "处方历史草稿id不能为空") Integer id, @NotNull(message = "处方历史草稿状态不能为空") Integer status) {
        presHistoryService.updatePresHistoryStatus(id, status);
        return ResponseEntity.ok().build();
    }

    /**
     * 查询处方历史草稿列表 分页
     *
     * @param req
     * @return
     */
    @GetMapping("/history/page")
    public ResponseEntity<IPage<PresHistoryPageRes>> queryPresHistoryPage(@Valid PresHistoryPageReq req) {
        IPage<PresHistoryPageRes> res = presHistoryService.queryPresHistoryPage(req);
        return ResponseEntity.ok(res);
    }

    /**
     * 查询处方历史草稿详情
     *
     * @param id
     * @return
     */
    @GetMapping("/history/detail")
    public ResponseEntity<PresHistoryDetailRes> queryPresHistoryDetail(@NotNull(message = "处方历史草稿id不能为空") Integer id) {
        PresHistoryDetailRes res = presHistoryService.queryPresHistoryDetail(id);
        return ResponseEntity.ok(res);
    }

    /**
     * 设置繁体 兼容数据 上线调一次废弃
     */
    @PostMapping("/set/traditional")
    public ResponseEntity<Void> setDrugTraditional() {
        drugsModelService.setDrugTraditional();
        return ResponseEntity.ok().build();
    }

//    /**
//     * 数据兼容处理
//     */
//    @PostMapping("/test")
//    public ResponseEntity<Void> test() {
//        presPrescriptionService.test();
//        return ResponseEntity.ok().build();
//    }

    /**
     * 处方再次发送到药房
     */
    @PostMapping("/send/phar/again")
    public ResponseEntity<Void> sendPharAgain(String orderNo) {
        presPrescriptionService.sendPharAgain(orderNo);
        return ResponseEntity.ok().build();
    }

    /**
     * 患者在线问诊咨询时查询处方历史诊断
     *
     * @param req
     * @return
     */
    @GetMapping("/med/page")
    public ResponseEntity<Page<PresPrescriptionMedPageRes>> queryPresMedPage(@Valid PresPrescriptionMedPageReq req) {
        Page<PresPrescriptionMedPageRes> res = presPrescriptionService.queryPresMedPage(req);
        return ResponseEntity.ok(res);
    }


    /**
     * 查询基础处方列表
     */
    @GetMapping("/basics/page")
    public ResponseEntity<IPage<PresBasics>> queryPresBasicPage(@Valid PresBasicReq req) {
        Page<PresBasics> page = presPrescriptionService.queryPresBasicPage(req);
        return ResponseEntity.ok(page);
    }

    /**
     * 查询详情
     */
    @GetMapping("/basics/detail")
    public ResponseEntity<PresBasics> queryPresBasicDetails(@RequestParam("basicsId") Integer basicsId) {
        PresBasics presBasics = presBasicsService.queryPresBasicDetails(basicsId);
        return ResponseEntity.ok(presBasics);
    }


    /**
     * 添加处方基础库
     */
    @PostMapping("/add/basics")
    public ResponseEntity<Void> addPresBasicDetails(@Valid @RequestBody PresBasicFrom from) {
        presBasicsService.addPresBasicDetails(from);
        return ResponseEntity.ok().build();
    }


    /**
     * 编辑处方库
     */
    @PostMapping("/update/basics")
    public ResponseEntity<Void> updatePresBasic(@Valid @RequestBody UpdatePresBasicFrom updatePresBasicFrom) {
        presBasicsService.updatePresBasic(updatePresBasicFrom);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除基础处方
     */
    @PostMapping("/update/basics/status")
    public ResponseEntity<Void> updatePresBasicsStatus(@RequestParam("basicsId") Integer basicsId) {
        presBasicsService.updatePresBasicsStatus(basicsId);
        return ResponseEntity.ok().build();
    }


    /**
     * 上下移动
     */
    @PostMapping("/move/basics")
    public ResponseEntity<Void> movePresBasics(@NotNull(message = "基础处方id不能为空") Integer basicsId, @NotNull(message = "上下移动标志不能为空") Integer flag) {
        presBasicsService.movePresBasics(basicsId, flag);
        return ResponseEntity.ok().build();
    }

    /**
     * 查询该药房下的药品
     */
    @GetMapping("/basic/drugs/batch")
    public ResponseEntity<List<DrugsBasicBatchRes>> queryDrugsBatch(@RequestParam("drugNames") String drugNames, @RequestParam("pharId") Integer pharId) {
        List<DrugsBasicBatchRes> resList = presBasicsService.queryDrugsBatch(drugNames, pharId);
        return ResponseEntity.ok(resList);
    }


    /**
     * 创建订单
     *
     * @param tencode
     * @param payType
     * @param openId
     */
    @PostMapping("/add/order")
    public ResponseEntity<PayOrderResponse<?>> addOrder(@NotBlank(message = "tencode处方编号不能为空") String tencode,
                                                        @NotBlank(message = "支付方式不能为空") String payType,
                                                        String openId,
                                                        HttpServletRequest request) {
        PayOrderResponse<?> response = presPrescriptionService.addOrder(openId, tencode, payType, request);
        return ResponseEntity.ok(response);
    }


    /**
     * 审核签方
     *
     * @param tencode
     */
    @PostMapping("/sign/name")
    public ResponseEntity<String> signName(@NotBlank(message = "处方编号不能为空") String tencode) {
        String url = presPrescriptionService.signName(tencode);
        return ResponseEntity.ok(url);
    }


    /**
     * 药师开方
     *
     * @param json
     */
    @PostMapping("/save/pharmacists")
    public ResponseEntity<String> savePharmacistsPres(@Valid @RequestBody String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        PresPharmacistsReq req = JSON.parseObject(jsonObject.getString("json"), PresPharmacistsReq.class);
        ValidatorUtils.verify(req, PresPharmacistsReq.class);
        String tencode = presPrescriptionService.savePharmacistsPres(req);
        return ResponseEntity.ok(tencode);
    }

    /**
     * 药师下单
     *
     * @param tencode
     */
    @PostMapping("/add/pharmacists/order")
    public ResponseEntity<Void> addPharmacistsOrder(@NotBlank(message = "tencode处方编号不能为空") String tencode) {
        presPrescriptionService.addPharmacistsOrder(tencode);
        return ResponseEntity.ok().build();
    }



    /**
     * 查询审方医生id
     */
    @GetMapping("/review/doctor/id")
    public ResponseEntity<Integer> queryReviewDoctorRes() {
        Integer doctorId = bindReviewPresDoctorService.queryReviewDoctorRes();
        return ResponseEntity.ok(doctorId);
    }


    /**
     * 查询是否接受
     */
    @GetMapping("/addPresIncomeDetail")
    public ResponseEntity<Void> addPresIncomeDetail() {
        presPrescriptionService.sendDDataToSupervise();
        return ResponseEntity.ok().build();
    }
}

